package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MRS
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    @Override
    public Result followOrNot(Long followUserId, Boolean isFollowed) {

        //获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        boolean result = false;
        //为true并且自己不能关注自己
       /* Follow iSfollow = this.getOne(new LambdaQueryWrapper<Follow>().eq(Follow::getFollowUserId, followUserId).eq(Follow::getUserId, userId));
        if (iSfollow != null) {
            //重复关注
            return Result.fail("请勿重复关注！");
        }*/
        if (BooleanUtil.isTrue(isFollowed) && userId !=  followUserId) {
            //关注
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            //保存
            result = this.save(follow);
            if (!result) {
                return Result.fail("关注失败！");
            }
            //将关注的用户id,放到redis的set集合中 sadd userId followerUserId
            stringRedisTemplate.opsForSet().add(key, followUserId.toString());

        } else {
            //取消关注
            result = this.remove(new LambdaQueryWrapper<Follow>().eq(Follow::getFollowUserId, followUserId).eq(Follow::getUserId, userId));
            if (!result) {
                return Result.fail("取消关注失败！");
            }

            //将关注的用户id,从redis的set集合中移除
            stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
        }

        return Result.ok();
    }

    @Override
    public Result isFollowed(Long followUserId) {
        Integer count = this.lambdaQuery().eq(Follow::getFollowUserId, followUserId).eq(Follow::getUserId, UserHolder.getUser().getId()).count();
        return Result.ok(count > 0);

    }

    @Override
    public Result followCommons(Long id) {

        //获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //当前登录用户
        String selfKey = "follows:" + userId;
        //关注的用户
        String followKey = "follows:" + id;

        //交集【每个登录用户关注后，会在redis的set集合中存放登录用户id的关注用户id元素集合】
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(selfKey, followKey);
        List<UserDTO> userDTOS = intersect.stream().map((uid) -> {
            //根据共同关注的用户id，查询对应的用户信息
            User user = userService.getById(Long.valueOf(uid));
            return BeanUtil.copyProperties(user, UserDTO.class);
        }).collect(Collectors.toList());

        return Result.ok(userDTOS);
    }
}
